package com.jun.controller.user;

import com.jun.pojo.entity.Food;
import com.jun.pojo.vo.R;
import com.jun.service.FoodService;
import com.jun.util.FoodUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/food")
public class FoodController {
  private static final Logger log = LoggerFactory.getLogger(FoodController.class);
  @Autowired
  private FoodService foodService;

  @GetMapping
  public R getFoodList(@RequestParam(value = "current", defaultValue = "1") int current,
                       @RequestParam(value = "size", defaultValue = "10") int size,
                       @RequestParam(value = "orderField", required = false) String orderField,
                       @RequestParam(value = "orderType", required = false) String orderType) {
    // 当没有设置排序或排序字段有误时,采用默认排序(智能排序)
    if (!FoodUtil.legalOrderField(orderField)) {
      orderField = null;
    }

    System.out.println(orderField + "::" + orderType);

    List<Food> foodList = foodService.foodList(current, size, orderField, orderType);
    return new R(foodList);
  }

  @GetMapping("/search")
  public R search(@RequestParam("search") String search) {
    log.info("输入值为 search = " + search);
    List<Food> foodList = foodService.searchFoodList(search);

    if (foodList.isEmpty()) {
      return new R().error();
    }

    return new R(foodList);
  }

  @GetMapping("/love/{userId}")
  public R getLoveList(@PathVariable("userId") Integer userId) {
    List<Food> foods = foodService.selectAll(userId);
    return new R(foods);
  }

}
